﻿using System;
using System.Collections.Generic;
using System.Text;

namespace NetFrame.Auto
{
    public static class MessageEncoding
    {
        /// <summary>
        /// 消息体序列化
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] Encode(object value)
        {
            SocketModel model = value as SocketModel;
            ByteArray ba = new ByteArray();
            ba.Write(model.Type);
            ba.Write(model.Area);
            ba.Write(model.Command);
            //判断消息体是否为空  不为空则序列化后写入
            if (model.Message != null)
            {
                ba.Write(SerializeUtil.Encode(model.Message));
            }
            byte[] result = ba.GetBuff();
            ba.Close();
            return result;
        }

        /// <summary>
        /// 消息体反序列化
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object Decode(byte[] value)
        {
            ByteArray ba = new ByteArray(value);
            SocketModel model = new SocketModel();
            byte type;
            int area;
            int command;
            //从数据中读取 三层协议  读取数据顺序必须和写入顺序保持一致
            ba.Read(out type);
            ba.Read(out area);
            ba.Read(out command);
            model.Type = type;
            model.Area = area;
            model.Command = command;
            //判断读取完协议后 是否还有数据需要读取 是则说明有消息体 进行消息体读取
            if (ba.Readable)
            {
                byte[] message;
                //将剩余数据全部读取出来
                ba.Read(out message, ba.Length - ba.Position);
                //反序列化剩余数据为消息体
                model.Message = SerializeUtil.Decode(message);
            }
            ba.Close();
            return model;
        }
    }
}
